/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.doc.sender.ui;


import com.sender.SimpleMD5;
import com.sender.mainWorkflow;
import com.database.entity.UserLogs;
import com.database.entity.UserUsers;
import database.senderUtil;
import java.awt.Frame;
import java.awt.Toolkit;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Calendar;
import javax.swing.JOptionPane;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author parent
 */
public class LoginFrame extends javax.swing.JFrame {

    /**
     * Creates new form LoginFrame
     */
    private boolean StatusLogin;
    private static mainWorkflow parent=null;

    public void setParent(mainWorkflow parents) {
        this.parent = parents;
    }
    public void setStatusLogin(boolean StatusLogin) {
        this.StatusLogin = StatusLogin;
    }
    public boolean getLoginStatus(){
        return StatusLogin;
    }
    
    public LoginFrame() {
        
        initComponents();
        setIcon();
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtUsername = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtPassWord = new javax.swing.JPasswordField();
        btnLogin = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Login to System");
        setModalExclusionType(java.awt.Dialog.ModalExclusionType.APPLICATION_EXCLUDE);
        setResizable(false);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Login"));

        jLabel1.setText("Username :");

        jLabel2.setText("Password :");

        btnLogin.setText("Login");
        btnLogin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLoginActionPerformed(evt);
            }
        });

        btnCancel.setText("Cancel");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(btnCancel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnLogin))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtUsername, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtPassWord))))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtPassWord, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnLogin)
                    .addComponent(btnCancel))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        java.awt.Dimension dialogSize = getSize();
        setLocation((screenSize.width-dialogSize.width)/2,(screenSize.height-dialogSize.height)/2);
    }// </editor-fold>//GEN-END:initComponents
    private void UpdateUserLog(int idValue,String status){
        try {
        setStatusLogin(status.equals("1"));
        parent.setLoginStatus(status.equals("1"));
        InetAddress ownIP=InetAddress.getLocalHost();
        Session session = senderUtil.getSessionFactory().getCurrentSession();
        String queryString = "from UserLogs where user_id = :id and ip_address=:ip";
        Query query = session.createQuery(queryString);  
        query.setInteger("id", idValue);  
        query.setString("ip", ownIP.getHostAddress());
        Object queryResult = query.uniqueResult(); 
        UserLogs userlog=(UserLogs)queryResult;
        if (userlog!=null){
        userlog.setLoginStatus(status);
        session.update(userlog);
        System.out.println("Update Session ...");
        } else {
                    UserLogs logu=new UserLogs();
                    logu.setIpAddress(ownIP.getHostAddress());
                    Calendar cal=Calendar.getInstance();
                    logu.setLastLogin(cal.getTime());
                    logu.setLoginStatus("1");
                    logu.setId(idValue);
                    session.save(logu);  
          System.out.println("Login Sukses...");          
        }
        parent.setUserID(idValue);
        session.getTransaction().commit(); 
        } catch (Exception ex){
//            ex.printStackTrace(); 
            System.out.println(ex.getMessage());
        }
    }
    public void ShowMainFrame(ArrayList<String> arrayText){
            PDFViewerFrame viewer= new PDFViewerFrame(true);
            viewer.setExtendedState(Frame.MAXIMIZED_BOTH);
            viewer.setStatusBarText(arrayText);
            viewer.setVisible(true);
    }
    private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLoginActionPerformed
        // TODO add your handling code here:
        Session session = senderUtil.getSessionFactory().openSession();
        Transaction tx=session.beginTransaction();
        try {
            
            String hql="from UserUsers where user_name=:username";
            SimpleMD5 md5enc=new SimpleMD5();
            
            String passe=new String(txtPassWord.getPassword());
            String passenk=md5enc.md5bit16(passe);
            //System.out.println(passenk);
            Query q = session.createQuery(hql);
            q.setString("username", txtUsername.getText());
            UserUsers users=(UserUsers)q.uniqueResult(); 
            if (users!=null){
//                System.out.println("Retrieval :" + users.getPassWord());   
                if (passenk.equals(users.getPassWord()))
                    {
                    //JOptionPane.showMessageDialog(this, "Password Benar");
                  int GroupID=users.getUserGroups().getId();                   
                  StatusLogin=true;
                  mainFrame utama=new mainFrame(GroupID);
                  utama.setUserID(users.getId());
                  utama.setJobID(users.getJobs().getId());
                  utama.setVisible(true);
                  UpdateUserLog(users.getId(), "1");  
                  tx.commit();  
//                    System.out.println("Password Benar");
                    this.dispose();
                } else {
                    StatusLogin=false;
                    parent.setLoginStatus(false);
                    JOptionPane.showMessageDialog(this, "Password Salah");
                    
                }
            session.getTransaction().commit();
            } else {
                JOptionPane.showMessageDialog(this, "Ada kesalahan Rekord");
            }
        } catch (Exception ex){
//           ex.printStackTrace(); 
            System.out.println(ex.getMessage());
//            System.exit(0);
        }
    }//GEN-LAST:event_btnLoginActionPerformed
private void setIcon() {
        setIconImage(Toolkit.getDefaultToolkit().
                getImage(getClass().getResource("/appicon.png")));
    }
    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_btnCancelActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(LoginFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(LoginFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(LoginFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(LoginFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new LoginFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnLogin;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPasswordField txtPassWord;
    private javax.swing.JTextField txtUsername;
    // End of variables declaration//GEN-END:variables
}
